package ydd.yykj.dl.com.rxflatmap;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import rx.Observable;
import rx.functions.Action1;
import rx.functions.Func1;

import static rx.schedulers.Schedulers.start;

public class MainActivity extends AppCompatActivity {
    Button button;
    TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.btn);
        tv = (TextView) findViewById(R.id.tv);
        initData();
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ss();
            }
        });
    }

    private void ss() {
        Observable.from(mSchoolClasses)
                .flatMap(new Func1<SchoolClass, Observable<Student>>() {
                    @Override
                    public Observable<Student> call(SchoolClass schoolClass) {
                        return Observable.from(schoolClass.getStudents());
                    }
                })
                .subscribe(new Action1<Student>() {
                    @Override
                    public void call(Student student) {
                        tv.append("\n"+student.name+","+student.age+"\n");
                    }
                });
    }

    class SchoolClass{
        Student[] stud;
        public SchoolClass(Student[] s){
            this.stud=s;
        }
        public Student[] getStudents(){
            return  stud;
        }
    }

    class Student{
        String name;
        String age;
        public Student(String name,String age){
            this.name=name;
            this.age=age;
        }
    }

    private SchoolClass[] mSchoolClasses=new SchoolClass[2];

    private void initData() {
        Student[] student=new Student[5];
        for(int i=0;i<5;i++){
            Student s=new Student("二狗"+i,"17");
            student[i]=s;
        }
        mSchoolClasses[0]=new SchoolClass(student);

        Student[] student2=new Student[5];
        for(int i=0;i<5;i++){
            Student s=new Student("小明"+i,"27");
            student2[i]=s;
        }
        mSchoolClasses[1]=new SchoolClass(student2);

    }
}
